package com.prd.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.prd.config.LoginInterceptor;
import com.prd.dto.SysMenuDTO;
import com.prd.dto.SysRoleDTO;
import com.prd.dto.SysUserDTO;
import com.prd.enums.BizCodeEnum;
import com.prd.enums.SysIsDeleteTyPeEnum;
import com.prd.mapper.SysMenuMapper;
import com.prd.mapper.SysUserRoleMapper;
import com.prd.model.*;
import com.prd.mapper.SysUserMapper;
import com.prd.service.SysRoleService;
import com.prd.service.SysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.prd.util.CommonUtil;
import com.prd.util.JWTUtil;
import com.prd.util.JsonData;
import com.prd.util.StringUtils;
import com.prd.vo.LoginUserVo;
import org.apache.commons.codec.digest.Md5Crypt;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 系统用户数据表 服务实现类
 * </p>
 *
 * @author lizhaoyi
 * @since 2024-01-09
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserDO> implements SysUserService {


    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysMenuMapper sysMenuMapper;

    /**
     * 获取用户列表
     *
     * @param userDTO
     * @return
     */
    @Override
    public List<SysUserDTO> selectUserList(SysUserDTO userDTO) {
        return sysUserMapper.selectUserList(CommonUtil.dtoTransfer(userDTO, SysUserDO.class));
    }

    /**
     * 获取当前用户信息
     *
     * @return
     */
    @Override
    public JsonData getCurrentUserInfo() {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();

        if (StringUtils.isNull(loginUser)) {
            return JsonData.buildError("用户不存在");
        }
        SysUserDO sysUserDO = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUserDO>()
                .eq(SysUserDO::getId, loginUser.getId())
                .eq(SysUserDO::getDeleted, SysIsDeleteTyPeEnum.UN_DELETE.getCode()));
        if (sysUserDO == null) {
            return JsonData.buildError("改管理用户不存在");
        }

        SysUserDTO sysUserDTO = CommonUtil.dtoTransfer(sysUserDO, SysUserDTO.class);

        //获取角色列表
        List<SysRoleDTO> sysRoleDTOS = sysRoleService.selectRoleByUserId(loginUser.getId());
        if (!CollectionUtils.isEmpty(sysRoleDTOS)) {

            sysUserDTO.setRoles(sysRoleDTOS);
        }
        //获取菜单列表
        List<SysMenuDO> menuDOList = sysMenuMapper.selectMenuListByRoleId(sysUserDTO.getRoleId());
        if (!CollectionUtils.isEmpty(menuDOList)) {
            sysUserDTO.setMenuDTOS(CommonUtil.dtoListTransfer(menuDOList, SysMenuDTO.class));
        }

        return JsonData.buildSuccess(sysUserDTO);
    }

    /**
     * 同步用户信息 TODO
     *
     * @return
     */
    @Override
    public JsonData syncUserInfo() {
        return null;
    }

    /**
     * 根据用户编号获取详细信息
     *
     * @param userId
     * @return
     */
    @Override
    public JsonData getUserInfoById(Long userId) {

        SysUserDO sysUserDO = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUserDO>()
                .eq(SysUserDO::getId, userId)
                .eq(SysUserDO::getDeleted, SysIsDeleteTyPeEnum.UN_DELETE.getCode()));

        if (sysUserDO == null) {
            return JsonData.buildError("用户不存在");
        }
        SysUserDTO sysUserDTO = CommonUtil.dtoTransfer(sysUserDO, SysUserDTO.class);

        //获取角色列表
        List<SysRoleDTO> sysRoleDTOS = sysRoleService.selectRoleByUserId(userId);
        sysUserDTO.setRoles(sysRoleDTOS);
        //获取菜单列表
        List<SysMenuDO> menuDOList = sysMenuMapper.selectMenuListByRoleId(sysUserDTO.getRoleId());
        sysUserDTO.setMenuDTOS(CommonUtil.dtoListTransfer(menuDOList, SysMenuDTO.class));

        return JsonData.buildSuccess(sysUserDTO);
    }

    /**
     * 根据用户编号获取授权角色
     *
     * @param userId
     * @return
     */
    @Override
    public JsonData getRolesByUserId(Long userId) {

        return JsonData.buildSuccess(sysRoleService.selectRoleByUserId(userId));
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param userDTO
     * @return
     */
    @Override
    public List<SysUserDTO> selectAllocatedList(SysUserDTO userDTO) {
        return sysUserMapper.selectAllocatedList(CommonUtil.dtoTransfer(userDTO,SysUserDO.class));
    }

    /**
     * 查询未分配用户角色列表
     *
     * @param userDTO
     * @return
     */
    @Override
    public List<SysUserDTO> selectUnallocatedList(SysUserDTO userDTO) {

        return sysUserMapper.selectUnallocatedList(CommonUtil.dtoTransfer(userDTO,SysUserDO.class));
    }

    /**
     * 用户授权角色
     *
     * @param userId
     * @param roleIds
     * @return
     */
    @Override
    public JsonData insertUserAuth(Long userId, Long[] roleIds) {

        //todo 判断是否有权限操作
        sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRoleDO>()
                .eq(SysUserRoleDO::getRoleId, userId));

        if (StringUtils.isNotEmpty(roleIds)) {
            List<SysUserRoleDO> userRoleDOS = new ArrayList<>();
            for (Long roleId : roleIds) {
                SysUserRoleDO sysUserRoleDO = new SysUserRoleDO();
                sysUserRoleDO.setUserId(userId);
                sysUserRoleDO.setRoleId(roleId);
                userRoleDOS.add(sysUserRoleDO);
            }
            sysUserRoleMapper.batchUserRole(userRoleDOS);
        }


        return JsonData.buildSuccess();
    }

    /**
     * 用户登录
     * @param loginUserVo
     * @return
     */
    @Override
    public JsonData login(HttpServletResponse response,LoginUserVo loginUserVo) {

        List<SysUserDO> userDOList = sysUserMapper.selectList(new LambdaQueryWrapper<SysUserDO>().eq(SysUserDO::getUsername, loginUserVo.getUsername()));
        if (userDOList != null && userDOList.size() == 1) {
            //已经注册
            SysUserDO sysUserDO = userDOList.get(0);
            String cryptPwd = Md5Crypt.md5Crypt(loginUserVo.getPassword().getBytes(), sysUserDO.getSalt());
            if (cryptPwd.equals(sysUserDO.getPassword())) {
                //登录成功,生成token
                LoginUser loginUser = LoginUser.builder().build();
                BeanUtils.copyProperties(sysUserDO, loginUser);
                String accessToken = JWTUtil.geneJsonWebToken(loginUser);

                //token存放cookie
                Cookie cookie = new Cookie("token",accessToken);
                //设置Cookie 过期时间为一天
                cookie.setMaxAge(86400);
                cookie.setPath("/");
                response.addCookie(cookie);

                return JsonData.buildSuccess(accessToken);

            } else {
                return JsonData.buildResult(BizCodeEnum.ACCOUNT_PWD_ERROR);
            }
        } else {
            //未注册
            return JsonData.buildResult(BizCodeEnum.ACCOUNT_UNREGISTER);
        }
    }


}
